package com.itwlj.controller.user;

import com.itwlj.dto.CartDTO;
import com.itwlj.entity.Cart;
import com.itwlj.result.Result;
import com.itwlj.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车
 */
@RestController
@RequestMapping("/member/cart")
@Api(tags = "C端购物车相关接口")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加购物车
     *
     * @param cartDTO
     * @return
     */
    @PostMapping
    @ApiOperation("添加购物车")
    public Result insert(@RequestBody CartDTO cartDTO) {
        log.info("添加购物车：{}", cartDTO);
        cartService.inset(cartDTO);

        return Result.success();
    }


    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping
    @ApiOperation("查看购物车")
    public Result<List<Cart>> list() {
        log.info("查看购物车");
        List<Cart> cartList = cartService.getByUserId();

        return Result.success(cartList);
    }

    /**
     * 合并购物车
     *
     * @return
     */
    @PostMapping("merge")
    @ApiOperation("合并购物车")
    public Result mergeCart(@RequestBody List<CartDTO> cartDTOList) {
        if (cartDTOList != null && !cartDTOList.isEmpty()) {
            log.info("合并购物车");
            cartDTOList.forEach(cartDTO -> {
                insert(cartDTO);
            });
        }

        return Result.success();
    }

    /**
     * 删除购物车商品
     *
     * @param skuId
     * @return
     */
    @DeleteMapping
    @ApiOperation("删除购物车商品")
    public Result deleteCart(@RequestParam Long skuId) {
        log.info("删除购物车商品skuId：{}", skuId);
        cartService.deleteBySkuId(skuId);
        return Result.success();
    }

    /**
     * 修改购物车商品数量
     *
     * @param skuId
     * @param count
     * @return
     */
    @PutMapping
    @ApiOperation("修改购物车商品数量")
    public Result updateCartCount(Long skuId, Long count) {
        log.info("修改购物车商品skuId：{}，数量：{}", skuId, count);
        cartService.updateCartCount(skuId, count);
        return Result.success();
    }
}
